//
//  OauthViewModel.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/19.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit

import SVProgressHUD

/// Oauth视图模型
class OauthViewModel {
    
    /// Oauth视图模型单例
    static let sharedOauthViewModel = OauthViewModel()
    
    /// 用户信息
    var oauthModel:OauthModel?
    
    /// token
    var access_token:String?{
        if !isExpiresd {
            
            return oauthModel?.access_token
        }
        return nil
    }
    
    /// token 是否过期
    var isExpiresd:Bool {
        
        if oauthModel?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            return false
        }
        
        print("过期了")
        
        return true
    }

    /// 用户是否已经登录
    var isLogin:Bool{
        
        return oauthModel?.access_token != nil && !isExpiresd
    }
    
    
    
    /// 用户头像URL
    var avatarUrl:NSURL{
        
        return NSURL(string:oauthModel?.avatar_large ?? "")!
    }
    
    var defaulImage:UIImage{
        
        return UIImage(named: "avatar_default_big")!
    }
    
    // MARK: - 构造方法
    private init(){
        
        oauthModel = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? OauthModel
        
        if isExpiresd {
            
            print("过期了")
            
            oauthModel = nil
        }
        
    }
    
    /// 归档保存路径
    var filePath:String {
        
        let filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        return (filePath as NSString) .stringByAppendingPathComponent("oauthModel.plist")
        
        
    }
}

// MARK: - 加载用户信息
extension OauthViewModel {
    
    ///  获取token,然后加载用户信息
    ///
    ///  - parameter code:           授权码
    ///  - parameter finishCallBack: 加载完成回调
    func getToken2LoadUserInfo(code:String, finishCallBack:(isSuccessed: Bool)->()) {
        
        // 获取令牌
        CXLAFNMangerTool.sharedAFNMangerTool.getToken(code) { (result, error) -> () in
            
            if error != nil {
                print("加载令牌出错了")
                finishCallBack(isSuccessed: false)
                return
            }
            
            let dict = result as! [String : AnyObject]
            
            self.oauthModel = OauthModel(dict: dict)
            
            self.loadUserInfo(self.oauthModel!, finishCallBack: finishCallBack)
        }
    }
    
    
    private func loadUserInfo(oauthModel:OauthModel,finishCallBack:(isSuccessed: Bool)->() ){
        
        // 加载用户信息
        CXLAFNMangerTool.sharedAFNMangerTool.getUserInfo(oauthModel.uid!, finishBlock: { (result, error) -> () in
            
            if error != nil {
                
                print("加载用户信息出错")
                
                SVProgressHUD.showErrorWithStatus("网络不给力,请稍后再试")
                
                finishCallBack(isSuccessed: false)
                return
            }
            
            guard let dict = result as? [String : AnyObject] else{
                
                print("数据格式错误")
                
                finishCallBack(isSuccessed: false)
                
                return
            }
            
            print(result)
            
            oauthModel.avatar_large = dict["avatar_large"] as? String
            oauthModel.screen_name = dict["screen_name"] as? String
            
            NSKeyedArchiver.archiveRootObject(oauthModel, toFile: self.filePath)
            
            finishCallBack(isSuccessed: true)
            
        })
    }
    

}
